package com.whfc.cncit.helmet.client;

import com.whfc.cncit.entity.CncitUpMsgR;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class HelmetClientHandler extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--register==============");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--unregistered==============");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--inactive==============");
    }

    // 连接成功后，向server发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("==============channel--active==============");

        for (int cnt = 0; cnt < 1; cnt++) {
            CncitUpMsgR msgR = new CncitUpMsgR();
            msgR.setDeviceCode("131910027100001");
            ctx.channel().writeAndFlush(msgR);
            TimeUnit.SECONDS.sleep(15);
        }

    }

    // 接收server端的消息，并打印出来
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        logger.info("==============channel--read==============");
        logger.info("the msg type is " + obj.getClass().getName());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
